import json

from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView

from common.utils import build_tree_menu
from menu.serializers import MenuSerializer
from menu.models import Menu


class MenuView(APIView):

    def get(self, request, *args, **kwargs):
        menus = Menu.objects.all().filter(level__gt=0)
        serializer = MenuSerializer(instance=menus, many=True)
        if request.query_params and request.query_params['type'] == 'tree':
            tree_data = build_tree_menu(serializer.data)
            return Response({'code': 200, 'msg': '获取菜单成功！', 'data': tree_data}, status=status.HTTP_200_OK)
        else:
            return Response({'code': 200, 'msg': '获取菜单成功！', 'data': serializer.data}, status=status.HTTP_200_OK)
